<template>
  <demo-content :title="title">
    <p></p>
    <canvas ref="canvasRef" width="600" height="400"></canvas>
  </demo-content>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";

const title = "鼠标追踪";
// 指定组件上的属性
defineOptions({ title });

const canvasRef = ref<HTMLCanvasElement>();

function generateRandomColor() {
  const s = "0123456789ABCDEF";
  let c = "#";
  for (let i = 0; i < 6; i++) {
    c += s[Math.ceil(Math.random() * 15)];
  }
  return c;
}

class Trail {
  canvas: HTMLCanvasElement;
  context: CanvasRenderingContext2D;
  center: { x: number; y: number };
  r: number;
  color: string;
  theta: number;
  prePos: { x: number; y: number };
  constructor(
    canvas: HTMLCanvasElement,
    center: { x: number; y: number },
    r: number,
    color: string
  ) {
    this.canvas = canvas;
    this.context = canvas.getContext("2d")!;
    this.center = center;
    this.r = r;
    this.color = color;
    this.theta = Math.random() * Math.PI * 2;
    this.prePos = {
      x: r * Math.cos(this.theta) + this.center.x,
      y: r * Math.sin(this.theta) + this.center.y,
    };
  }
  dr() {
    this.theta += 0.05;
    const newPos = {
      x: this.r * Math.cos(this.theta) + this.center.x,
      y: this.r * Math.sin(this.theta) + this.center.y,
    };
    this.context.save();
    this.context.strokeStyle = this.color;
    this.context.lineWidth = 3;
    this.context.beginPath();
    this.context.moveTo(this.prePos.x, this.prePos.y);
    this.context.lineTo(newPos.x, newPos.y);
    this.context.stroke();
    this.prePos = newPos;
    this.context.restore();
  }
}

onMounted(() => {
  console.log("inner: ", innerWidth, innerHeight);
  const canvas = canvasRef.value!;
  const mousePos = { x: canvas.width / 2, y: canvas.height / 2 };
  canvas.addEventListener("mousemove", (e) => {
    // console.log("e2: ", e.offsetX, e.offsetY);
    mousePos.x = e.offsetX;
    mousePos.y = e.offsetY;
  });

  const ctx = canvas.getContext("2d")!;
  ctx.save();
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.restore();
  const trails: Trail[] = [];
  for (let i = 0; i < 30; i++) {
    trails.push(
      new Trail(canvas, mousePos, Math.random() * 100, generateRandomColor())
    );
  }
  function draw() {
    ctx.save();
    ctx.fillStyle = "#00000008";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.restore();
    trails.forEach((t) => t.dr());
    requestAnimationFrame(draw);
  }
  requestAnimationFrame(draw);
});
</script>

<style src="./default.css" scoped></style>
